﻿namespace PESWebMVC.Filters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    using System.Web.Http.ModelBinding;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ModelValidationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext _actionContext)
        {
            if (_actionContext.ModelState.IsValid) return;

            // Return the validation errors in the response body.
            var errors = new Dictionary<string, IEnumerable<string>>();
            foreach (KeyValuePair<string, ModelState> keyValue in _actionContext.ModelState)
            {
                errors[keyValue.Key] = keyValue.Value.Errors.Select(_e => _e.ErrorMessage);
            }

            _actionContext.Response =
                _actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
        }
    }
}